// Register page module
// ====================

define(['zepto', 'wx', 'wxutil','sui'], function($, wx, wxutil) {
  return {
    init: function(jsConfig) {
      // config WeChat JS SDK
      wxutil.config(jsConfig, 'scanQRCode')
      this.onClickActivateButton()
    },
    
    /**
     * Click handler for activate coupon button
     */
    onClickActivateButton: function() {
      var that = this
      $('.button-claim').on('click', function(e) {
        e.preventDefault()
        wx.ready(function() {
          wx.scanQRCode({
        	needResult: 1,
        	scanType: ['qrCode'],
        	success: function(res) {
        	  that.scanQRCodeSuccess(res)
            }
          })
        })
      })
    },

    /**
     * Callback to process QR scan result
     */
    scanQRCodeSuccess: function(result) {
      var that = this;
      if(result !== null && result.resultStr !== null) {
        console.log("redirect to activate coupon page with res:" + result.resultStr)
        that.activateSubmit(result.resultStr)
      }
    },
    
    activateSubmit: function (url) {
        $.ajax({
        	type: 'POST',
        	url: url,
        	data: {'_method' : 'PATCH'}
        }).done(function(response){
        	response = JSON.parse(response)
        	if(response.code == 0) {
        		location.href = window.__CTX__.root + response.data.url + '?message=' + response.message;
        	} else {
        		$.toast(response.message)
        		setTimeout(function() {
        			location.href = window.__CTX__.root + response.data.url;
        		}, 2000)
        	}
        })
    }
  }
})